package scala.cookbook.akka

import akka.actor._
import akka.pattern.{Backoff, BackoffSupervisor}
import scala.concurrent.duration._

/**
  * Created by baiwf on 2017/5/13.
  */

private class Kenny1 extends Actor {
  override def receive: Receive = {
    case _ => println("kenny recv a msg")
  }
}

class Parent1 extends Actor {
  val childProps = Props[Kenny1]
  val kenny = context.actorOf(childProps, name = "kenny")
  context.watch(kenny)

  override def receive: Receive = {
    case Terminated(kenny) => println("OMG, they killed Kenny")
    case _ => println("parent recv a msg")
  }


  //akka 文档 3.4节
  val supervisor = BackoffSupervisor.props(
    Backoff.onFailure(
      childProps,
      childName = "kenny",
      minBackoff = 3.seconds,
      maxBackoff = 30.seconds,
      randomFactor = 0.2
    ).withAutoReset(10.seconds)
    .withSupervisorStrategy(
      OneForOneStrategy() {
        case _: IllegalArgumentException => SupervisorStrategy.restart
        case _ => SupervisorStrategy.escalate
      }
    )
  )

}

object WatchActor extends App {
  val sys = ActorSystem("DeathWatchTest")
  val parent = sys.actorOf(Props[Parent1], name = "parent") //name imply hirarchical path
  val kenny = sys.actorSelection("/user/parent/kenny")

  kenny ! PoisonPill
  Thread.sleep(3000)
  println("shudown...")
  sys.shutdown()
}
